<?php

class NotificationsController extends \Phalcon\Mvc\Controller
{

    public function indexAction()
    {

    }
    public function countUnreadAction()
    {
        $user_id = $this->session->get('user_id');
        
        $friend = ConnectionRequestTb::find(array(
                "conditions"=>"receiver_id = ?0",
                "bind"=>array(0=>$user_id)
            ))->count();
        $notif = Notification::find(array(
                "conditions"=>"receiver_id = ?0 AND has_read = 0",
                "bind"=>array(0=>$user_id)
            ))->count();
        $result = array(
                "friend"=>$friend,
                "notification"=>$notif
            );
        echo json_encode($result);
        $this->view->disable();

    }

    public function listAction($page='')
    {
    	$currentPage = ($page != '') ? $page : 1;
    	$receiver_id = $this->session->get('user_id');
    	
    	$data = Notification::listNotification($receiver_id);
  	  	
	
	    $paginator = new \Phalcon\Paginator\Adapter\Model(array(
				        "data"  => $data,
				        "limit" => 5,
				        "page"  => $currentPage
	        		));

    	$page = $paginator->getPaginate();

    	foreach ($page->items as $value) {
    		$result[] = array(
    				"notif_id"=>(string) $value->nit->id,
    				"receiver_id"=>$value->nit->receiver_id,
    				"date_created"=>$value->nit->date_created,
    				"has_read"=>$value->nit->has_read,
    				"type"=>$value->nit->type,
    				"data"=>json_decode($value->nit->params)
    			);	
    	}
    
    	echo json_encode($result);
    	$this->view->disable();
    }

    public function markAction()
    {
        if(!$this->request->isPost()) die('not a post');
        $notif_id = $this->request->getPost('notif_id');
        $notif = Notification::findFirstById($notif_id);
        $notif->has_read = 1;
        echo @$notif->save();
        $this->view->disable();

    }

}

